var util = require('../../utils/md5.js')
//获取应用实例  
var app = getApp()  


Page({
  data: {
    items: [
      '求助',
      '闲置',
      '兼职',
      '租房',
      '寻物',
      '招领',
      '投稿',
      '表白',
    ],
    length:0,
    host: '',
    dir: '',
    accessKeyId: '',
    imgs:[],
    imgstwo:[],
    policy: '',
    img: "",
    value:'',
    signature: '',
    index: 1,
    list:[],
    hidden:true,
    example: {
      classNames: 'wux-animate--fadeIn',
      enter: true,
      exit: true,
      in: false,
    },
    show: false,
    status: '',
    imgWidth: 0,
    imgHeight: 0
  },
  descInput: function (e){
    this.setData({
      value: e.detail.value,
      length: e.detail.cursor
    })
   
  },
  
  upload() {
    var that = this
    var i = that.data.imgs.length 

    wx.chooseImage({
      count: 9-i, // 最多可以选择的图片张数，默认9
      sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        const ctx = wx.createCanvasContext('firstCanvas');
        var images = res.tempFilePaths

       
          var aliyunFileKey = new Date().getTime() + Math.floor(Math.random() * 150)+ '.jpg';
          // var images= that.data.list
          if(images.length<=1){
          wx.uploadFile({
            url: that.data.host,
            filePath: images[0],
            name: 'file',
            formData: {
              name: images[0],
              key: that.data.dir + aliyunFileKey,
              policy: that.data.policy,
              OSSAccessKeyId: that.data.accessKeyId,
              success_action_status: "200",
              signature: that.data.signature
            },
            success: function (res) {
              var imgs = that.data.imgs
              var imgstwo = that.data.imgstwo
              imgs.push(that.data.dir + aliyunFileKey)
              imgstwo.push(that.data.host + that.data.dir + aliyunFileKey)
              that.setData({
                imgs: imgs,
                imgstwo: imgstwo
              })
             
              if(that.data.imgs.length>8){
                wx.showModal({
                  title: '提示',
                  content: '最多九张图',
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })
                that.setData({
                  hidden: false
                })
              }else{
                that.setData({
                  hidden: true
                })
              }

            },
            fail: function ({
              errMsg
            }) {
         
              wx.showToast({
                title: "上传失败",
                duration: 1000
              })
            },
          })
          }else {
            for(var i = 0;i<images.length;i++){
              let list= images[i].slice(9);
          
              wx.uploadFile({
                url: that.data.host,
                filePath: images[i],
                name: 'file',
                formData: {
                  name: images[i],
                  key: that.data.dir+list,
                  policy: that.data.policy,
                  OSSAccessKeyId: that.data.accessKeyId,
                  success_action_status: "200",
                  signature: that.data.signature
                },
                success: function (res) {
      
                  var imgs = that.data.imgs
                  var imgstwo = that.data.imgstwo
          
                  imgs.push(that.data.dir +list)
                  imgstwo.push(that.data.host + that.data.dir +list)
                  that.setData({
                    imgs: imgs,
                    imgstwo: imgstwo
                  })
             
                  if (that.data.imgs.length > 8) {
                    // wx.showModal({
                    //   title: '提示',
                    //   content: '最多九张图',
                    //   success: function (res) {
                    //     if (res.confirm) {
                    //       console.log('用户点击确定')
                    //     } else if (res.cancel) {
                    //       console.log('用户点击取消')
                    //     }
                    //   }
                    // })
                    that.setData({
                      hidden: false
                    })
                  } else {
                    that.setData({
                      hidden: true
                    })
                  }
      
                },
                fail: function ({
                  errMsg
                }) {
             
                  wx.showToast({
                    title: "上传失败",
                    duration: 1000
                  })
                },
              })
            }
          }
        }
        
        
      
    })
  },

  pickerChange(e) {
    const index = e.detail.value
    const value = this.data.items[index]
    const classNames = `wux-animate--${value}`
    this.setData({
      index,
      'example.classNames': classNames,
    })
  },
  btn(e){
    var that = this;
    let openid = wx.getStorageSync('openid');
    let authorization = wx.getStorageSync('authorization');
    let url = wx.getStorageSync('url');
    let type = parseInt(that.data.index)+1;

    if (that.data.value==''){
      wx.showModal({
        title: '提示',
        content: '内容不能为空',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')

          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      wx.request({
        url: url + "/v1/article",
        data: {
          description: that.data.value,
          image: that.data.imgs.toString(),
          type: type
        },
        method: "post",
        header: {
          'content-type': 'application/json',
          'authorization': authorization,
          'openid': wx.getStorageSync('openid')
        },
        success: function (res) {
          wx.showToast({
            title: "发帖成功",
            icon: 'success',
            duration: 1000
          })
          that.setData({
            value: '',
            imgs: [],
            index: 0,
            length:0
          })
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
      
    }
    
  },
  del(e){
    var that = this;
    var imgs = that.data.imgs
    that.data.imgs.splice(e.currentTarget.dataset.index, 1)
    that.setData({
      imgs:imgs,
      hidden: true
    })
  },
 
  onLoad: function(options) {
    var that = this;
    let openid = wx.getStorageSync('openid');
    let authorization = wx.getStorageSync('authorization');
    let url = wx.getStorageSync('url');
    wx.request({
      url: url + "/v1/oss",
      data: {
        openId: openid
      },
      method: "get",
      header: {
        'content-type': 'application/json',
        'authorization': authorization,
        'openid': wx.getStorageSync('openid')
      },
      success: function(res) {
        
        wx.setStorageSync('host', res.data.data.ossResponse.host);
        that.setData({
          host: res.data.data.ossResponse.host,
          dir: res.data.data.ossResponse.dir,
          accessKeyId: res.data.data.ossResponse.accessKeyId,
          policy: res.data.data.ossResponse.policy,
          signature: res.data.data.ossResponse.signature,
        })

      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})